﻿using System;
using System.Windows.Forms;
using TicTacToe.Opponents;

namespace TicTacToe.WinForms
{
    public partial class TicTacToeUI : Form
    {
        private readonly GameController _game;

        public TicTacToeUI()
        {
            InitializeComponent();

            _game = new GameController();
            _game.CellFilled += OnGameCellFilled;
            _game.NewGame += (o, e) => boardControl.Reset();
            _game.StatusChanged += (o, e) => statusLabel.Text = e.Status;

            boardControl.CellClicked += OnBoardCellClicked;
            cbOpponent.DataSource = _game.AvailableOpponents;
            cbOpponent.DisplayMember = "Name";

            _game.BeginGame();
        }

        private void OnGameCellFilled(object sender, CellFilledEventArgs e)
        {
            boardControl.SetCellContents(e.Location, e.Symbol);
        }

        private void OnBoardCellClicked(object sender, CellClickedEventArgs e)
        {
            try
            {
                _game.MakePlayerMove(e.CoOrdinates);
            }
            catch (InvalidMoveException ex)
            {
                MessageBox.Show(ex.Message, "Invalid Move", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Unexpected Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void OnNewGameClicked(object sender, EventArgs e)
        {
            try
            {
                _game.BeginGame();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Unexpected Error Starting New Game", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void OnNewOpponentSelected(object sender, EventArgs e)
        {
            try
            {
                _game.CurrentOpponent = (IOpponent)cbOpponent.SelectedItem;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Unexpected Error Choosing Opponent", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}